package cn.steel.service.impl;

import cn.steel.domain.entity.Message;
import cn.steel.mapper.MessageMapper;
import cn.steel.service.MessageService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
public class MessageServiceImpl implements MessageService {

    private final MessageMapper messageMapper;
    private final RedisTemplate<String, Object> redisTemplate;

    private static final String UNREAD_COUNT_KEY = "unread:count:";

    @Override
    @Transactional
    public void sendMessage(Long senderId, Long receiverId, String content) {
        Message message = new Message();
        message.setSenderId(senderId);
        message.setReceiverId(receiverId);
        message.setContent(content);
        message.setIsRead(false);
        message.setCreateTime(LocalDateTime.now());
        messageMapper.insertMessage(message);

        // 更新未读消息计数
        String redisKey = UNREAD_COUNT_KEY + receiverId;
        Long count = getUnreadCountFromRedis(redisKey);
        redisTemplate.opsForValue().set(redisKey, count + 1L); // 确保存储为 Long 类型
        log.info("Message sent: senderId={}, receiverId={}, content={}", senderId, receiverId, content);
    }

    @Override
    public List<Message> getMessagesBetweenUsers(Long senderId, Long receiverId) {
        return messageMapper.findMessagesBySenderAndReceiver(senderId, receiverId);
    }

    @Override
    @Transactional
    public void markMessagesAsRead(Long senderId, Long receiverId) {
        //获取双向消息
        List<Message> messages = messageMapper.findMessagesBySenderAndReceiver(senderId, receiverId);
        for (Message message : messages) {

            if (!message.getIsRead() && message.getReceiverId().equals(receiverId)) {
                messageMapper.updateMessageReadStatus(message.getId(), true);
            }
        }
        // 重新计算未读消息数量并更新 Redis
        long updatedCount = messageMapper.findUnreadMessagesByReceiver(receiverId).size();
        redisTemplate.opsForValue().set(UNREAD_COUNT_KEY + receiverId, updatedCount);
        log.info("Messages marked as read: senderId={}, receiverId={}, updated unread count={}", senderId, receiverId, updatedCount);
    }

    @Override
    public long getUnreadMessageCount(Long receiverId) {
        String redisKey = UNREAD_COUNT_KEY + receiverId;
        Long count = getUnreadCountFromRedis(redisKey);
        if (count == null) {
            count = (long) messageMapper.findUnreadMessagesByReceiver(receiverId).size();
            redisTemplate.opsForValue().set(redisKey, count); // 确保存储为 Long 类型
        }
        return count;
    }

    // 辅助方法：从 Redis 获取未读消息计数，并处理类型转换
    private Long getUnreadCountFromRedis(String redisKey) {
        Object countObj = redisTemplate.opsForValue().get(redisKey);
        if (countObj == null) {
            return 0L;
        }
        if (countObj instanceof Integer) {
            return ((Integer) countObj).longValue();
        } else if (countObj instanceof Long) {
            return (Long) countObj;
        } else {
            log.warn("Unexpected type for unread count in Redis: {}", countObj.getClass());
            return 0L;
        }
    }
}